package com.xbq.lock;

import redis.clients.jedis.Jedis;

/**
 * 锁
 * @author Administrator
 *
 */
public class LockUtil {

	/**
	 * 设置 key value 和过期时间
	 * @param key
	 * @param value
	 * @param expireTime
	 * @return
	 * @throws Exception
	 */
	public static Long Setnx(String key, String value, int expireTime) throws Exception {
		Jedis jedis = null;
		try {
			jedis = JedisUtil.common();
			Long ret = jedis.setnx(key, value);
			if (ret == 1 && expireTime > 0) {
				jedis.expire(key, expireTime);
			}
			return ret;
		} catch (Exception e) {
			throw e;
		} finally {
//			JedisUtil.closeAll();
		}
	}

	/**
	 * 设置 key value 过期时间  （原子性的）
	 * @param key
	 * @param value
	 * @param expireTime
	 * @return
	 * @throws Exception
	 */
	public static String Setex(String key, String value, int expireTime) throws Exception {
		Jedis jedis = null;
		try {
			jedis = JedisUtil.common();

			String ret = jedis.setex(key, expireTime, value);
			return ret;
		} catch (Exception e) {
			throw e;
		} finally {
//			JedisUtil.closeAll();
		}
	}

	/**
	 * 根据key获取 value
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String GSetnx(String key) throws Exception {
		Jedis jedis = null;
		try {
			jedis = JedisUtil.common();
			return jedis.get(key);
		} catch (Exception e) {
			throw e;
		} finally {
//			JedisUtil.closeAll();
		}
	}
	
	public static Long Del(String key) throws Exception {
		Jedis jedis = null;
		try {
			jedis = JedisUtil.common();
			return jedis.del(key);
		} catch (Exception e) {
			throw e;
		} finally {
//			JedisUtil.closeAll();
		}
	}
	
}
